# coding=utf-8
import json
import random
import base64
import time
import rsa
import requests

from abchina.util.aes_util import AesCrypter


class SecurityUtil(object):
    modulus = 'C0D0DB60545A161398274F06DA1A412988E74D37B080B9A1BB543CE175DB055E57BF441954F7D636F357326E6EAE4383D3F05E489CCF3CD29EF88AC7FBF4FDA5C4D71AC794348907100CA7776CC31D6B57A4C7DA94C41DCEDE17F31515C7EEF5E8168487B2F76BA73EE861868264CB880B3CB2149A14606AC78AB2A50AECDBB7'
    exponent = '010001'

    def get_keys(self):
        key = self.random_str(32)
        iv = self.random_str(16)
        timestamp = str(int(round(time.time())))

        # rsa
        token = key + '|' + iv
        rsa_result = self.rsa_encrypt(token)

        # aes
        aes = AesCrypter(key, iv)
        enc_msg = aes.encrypt(
            json.dumps({
                'Key': rsa_result
            })
        )
        integrity_hash = aes.hmac_sha1_sign(enc_msg, timestamp.encode())
        r = requests.post(
            'https://e.abchina.com/qyjc/site/Security/UpdateEncrypt',
            json=json.dumps({
                'Key': rsa_result
            }),
            cookies={
                'GroupPurchaseSessionId': 's1ywvp0qdyrwribmq2fq1zz3',
                'BIGipServerpool_ebiz_9000': '2dF0uzl8grpnCjwI76szeJ2T4xRfJEiwTRvCP2qa8Or0nBihlfJG3jjsi7PNmMsWxQqh264am6QgXTk=',
                'BIGipServerpool_ebiz_qyjc': 'rAIb01Ej52hqgfD52ToaBwl+hWQFkL0mCDl6yGx8Hrwdh/MIHag00eymXK2QvfqWCVNaxtepS1gDfcU='
            },
            headers={
                'Content-Type': 'application/json;charset=UTF-8',
                # 'X-EncryptType': 'encrypt',
                'X-Timestamp': timestamp,
                'X-IntegrityHash': integrity_hash,
            }
        )

        print(r.text)

    def rsa_encrypt(self, message):
        modulus = int(self.modulus, 16)
        exponent = int(self.exponent, 16)
        rsa_pubkey = rsa.PublicKey(modulus, exponent)
        crypto = rsa.encrypt(message.encode(), rsa_pubkey)
        enc_msg = base64.b64encode(crypto)
        print(enc_msg)

        return str(enc_msg, encoding='utf-8')

    def random_str(self, len=32):
        """
        生成随机字符串
        :param len: 长度
        :return:
        """
        return ''.join(
            random.sample([
                'z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g', 'f',
                'e', 'd', 'c', 'b', 'a', 'Z', 'Y', 'X', 'W', 'V', 'U', 'T', 'S', 'R', 'Q', 'P', 'O', 'N', 'M', 'L', 'K',
                'J', 'I', 'H', 'G', 'F', 'E', 'D', 'C', 'B', 'A', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
            ], len)
        )


if __name__ == '__main__':
    SecurityUtil().get_keys()
